package com.example.admin.controller;

import com.example.admin.service.CategoryService;
import com.example.xo.common.Result;
import com.example.xo.pojo.Category;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author linzinan
 */
@RestController
@Slf4j
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping("")
    public Result add(@RequestBody Category category){
        if(category.getCategoryName().length()>20){
            log.info("分类{}字符个数超过20",category.getCategoryName());
            return Result.error();
        }
        return Result.success(categoryService.add(category));
    }

    @GetMapping
    public Result findAll(){
        List<Category> list = categoryService.findAll();
        return Result.success(list);
    }

    @GetMapping("{id}")
    public Result findById(@PathVariable String id){
        Category category = categoryService.findById(id);
        return Result.success(category);
    }

    @DeleteMapping("{id}")
    public Result deleteById(@PathVariable String id){
        boolean result = categoryService.deleteById(id);
        if (result){
            return Result.success(null);
        }
        return Result.error();
    }

    @PutMapping()
    public Result update(@RequestBody Category category){
        log.info("收到修改请求，{}",category);
        //长度不能超过20个字
        if(category.getCategoryName().length()>20){
            //记录给程序员
            log.info("分类{}长度超过20个字",category.getCategoryName());
            return Result.error();
        }

        boolean res = categoryService.update(category);
        return Result.success(res);
    }
}
